package com.dunshan.dunshanfile.controller;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author dunshan
 * @program: dunshan-pef
 * @description: 文件上传Deom
 * @date 2021-11-09 12:50:39
 */
@Log4j2
@Controller
public class FileController {

    private final RateLimiter limiter = RateLimiter.create(2.0);
    private DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file) {
        HashMap<String, Object> map = new HashMap<>();
//        boolean tryAcquire = limiter.tryAcquire(500, TimeUnit.MILLISECONDS);
//        if (!tryAcquire) {
//            log.warn("进入服务降级，时间{}", LocalDateTime.now().format(dtf));
//            map.put("data", "error 当前排队人数较多，请稍后再试！");
//            return map;
//        }

        if (StringUtils.isEmpty(file)) {
            return map.put("data", "file is null");
        }
        long time = System.currentTimeMillis();
        String fileName = file.getOriginalFilename();
        String path = "/Users/liwen406/Desktop/tmp";
        File dest = new File(String.format("%s/data/%s-%s", path, time, fileName));
        System.out.println(dest.getAbsolutePath());
        if (!dest.getParentFile().exists()) {
            //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
            map.put("data", "ok");
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map.put("data", "error");
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws FileNotFoundException, UnsupportedEncodingException {
        String path = this.getClass().getClassLoader().getResource("").getPath();
        File dest = new File(path + "/data/" + name);
        // 下载本地文件
        // 读到流中
        InputStream inStream = new FileInputStream(dest.getAbsolutePath());// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + name);
        // 循环取出流中的数据
        byte[] b = new byte[1024];
        int len;
        try {
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//

//        if (dest.exists()) { //判断文件父目录是否存在
////            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("application/force-download");
//            response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(name, "UTF-8"));
//            byte[] buffer = new byte[1024];
//            FileInputStream fis = null; //文件输入流
//            BufferedInputStream bis = null;
//
//            OutputStream os = null; //输出流
//            try {
//                os = response.getOutputStream();
//                fis = new FileInputStream(dest);
//                bis = new BufferedInputStream(fis);
//                int i = bis.read(buffer);
//                while (i != -1) {
//                    os.write(buffer);
//                    i = bis.read(buffer);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            System.out.println("----------file download---" + name);
//            try {
//                bis.close();
//                fis.close();
//                try {
//                    Thread.sleep(90);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }

        log.info("下载完毕");
    }
}
